package org.happen.android.util;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.NetworkInfo.State;

public class UtilNetwork
{

	//网络状态
	public enum InternetState
	{
		MOBILE_CONNECTED, WIFI_CONNECTED, WIFI_MOBILE, NONE
	}

	/**
	 * Judge network was clear 判断网络是否打开
	 * 
	 * @param context
	 * @return
	 */
	public static boolean isNetworkAvailable(Context context)
	{
		final ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		final NetworkInfo networkInfo = cm.getActiveNetworkInfo();
		if (networkInfo != null && networkInfo.isConnectedOrConnecting())
		{
			return true;
		}
		return false;
	}

	/**
	 * judge networkAvailable 判断网络是否可用
	 * 
	 * @param context
	 * @return
	 */
	public static boolean checkConnection(Context context)
	{
		final ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		final NetworkInfo networkInfo = cm.getActiveNetworkInfo();
		if (networkInfo == null || !networkInfo.isConnectedOrConnecting())
		{
			return false;
		}
		return true;
	}

	public static InternetState getNetworkConnectionState(Context context)
	{
		State wifiState = null;
		State mobileState = null;
		ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo info = null;
		if ((info = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI)) != null)
		{
			wifiState = info.getState();
		}
		if ((info = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI)) != null)
		{
			mobileState = info.getState();
		}
		if (State.CONNECTED != wifiState && State.CONNECTED == mobileState)
		{
			// 手机网络连接成功  
			return InternetState.MOBILE_CONNECTED;
		} else if (State.CONNECTED == wifiState && State.CONNECTED == mobileState)
		{
			// 两种网络均连接
			return InternetState.WIFI_MOBILE;
		} else if (State.CONNECTED == wifiState && State.CONNECTED != mobileState)
		{
			// 无线网络连接成功  
			return InternetState.WIFI_CONNECTED;
		}
		//没有网络
		return InternetState.NONE;
	}

}
